import type React from 'react';
import { useMemo, useState } from 'react';
import { Select, Space, Typography, Alert, Tooltip, Button, message, Input } from 'antd';
import { InfoCircleOutlined } from '@ant-design/icons';

const { Paragraph, Text } = Typography;

const fields = [
  { key: 'second', label: '秒', tips: '0-59之间的整数' },
  { key: 'minute', label: '分', tips: '0-59之间的整数' },
  { key: 'hour', label: '时', tips: '0-23之间的整数' },
  { key: 'day', label: '日', tips: '1-31之间的整数，或 "?" 占位符' },
  { key: 'month', label: '月', tips: '1-12之间的整数' },
  { key: 'week', label: '周', tips: '1-7之间的整数（1=周日），或 "?" 占位符' },
  { key: 'year', label: '年', tips: '留空或指定4位年份，例如2025' },
];

const commonOptions = ['*', '*/5', '*/10', '0', '?'];

function describeField(field: string, unit: string): string {
  if (field === '*') return `每${unit}`;
  if (field === '?') return `不指定${unit}`;
  if (field.includes('/')) {
    const [start, step] = field.split('/');
    return `从${start === '*' ? '0' : start}${unit}开始，每${step}${unit}`;
  }
  if (field.includes('-')) {
    const [start, end] = field.split('-');
    return `${start}-${end}${unit}`;
  }
  if (field.includes(',')) {
    return `${unit}${field.split(',').join('、')}`;
  }
  if (field.endsWith('L')) {
    return unit === '日' ? '本月最后一天' : `本月最后一个星期${field[0]}`;
  }
  if (field.includes('W')) {
    return `离${field.replace('W', '')}号最近的工作日`;
  }
  if (field.includes('#')) {
    const [weekday, index] = field.split('#');
    return `每月第${index}个星期${weekday}`;
  }
  return `${unit}${field}`;
}

const explainCron = (expression: string) => {
  const [second, minute, hour, day, month, week, year = '*'] = expression.split(' ');

  return `计划在：${describeField(year, '年')}，` +
         `${describeField(month, '月')}，` +
         `${describeField(day, '日')}，` +
         `${describeField(week, '星期')}，` +
         `${describeField(hour, '时')}，` +
         `${describeField(minute, '分')}，` +
         `${describeField(second, '秒')} 执行。`;
};

const quickTemplates = [
  { label: '每分钟', value: '0 */1 * * * ?' },
  { label: '每小时', value: '0 0 */1 * * ?' },
  { label: '每天 12:00', value: '0 0 12 * * ?' },
  { label: '每周一 9:00', value: '0 0 9 ? * 2' },
];

const CronGenerator: React.FC<{
  value?: string;
  onChange?: (val: string) => void;
}> = ({ value, onChange }) => {
  const [cron, setCron] = useState<Record<string, string>>({
    second: '0',
    minute: '*',
    hour: '*',
    day: '*',
    month: '*',
    week: '?',
    year: '',
  });

  const expression = useMemo(() => {
    return `${cron.second} ${cron.minute} ${cron.hour} ${cron.day} ${cron.month} ${cron.week} ${cron.year}`.trim();
  }, [cron]);

  const isValid = useMemo(() => /^(\S+\s+){5,6}\S+$/.test(expression), [expression]);

  const handleChange = (key: string, val: string) => {
    const next = { ...cron, [key]: val };
    setCron(next);
    const expr = `${next.second} ${next.minute} ${next.hour} ${next.day} ${next.month} ${next.week} ${next.year}`.trim();
    onChange?.(expr);
  };

  const handleQuickSet = (val: string) => {
    const [second, minute, hour, day, month, week, year = ''] = val.split(' ');
    const parts = { second, minute, hour, day, month, week, year };
    setCron(parts);
    onChange?.(val);
  };

  return (
    <Space direction="vertical" size="large" style={{ width: '100%' }}>
      {fields.map(({ key, label, tips }) => (
        <Space key={key} style={{ display: 'flex' }}>
          <Tooltip title={tips}>
            <Text strong>{label}</Text>
            <InfoCircleOutlined style={{ marginLeft: 4, color: '#999' }} />
          </Tooltip>
          <Select
            showSearch
            style={{ width: 200 }}
            value={cron[key]}
            onChange={(val) => handleChange(key, val)}
            options={commonOptions.map((val) => ({ label: val || '(空)', value: val }))}
            dropdownRender={(menu) => (
              <>
                {menu}
                <div style={{ padding: 8 }}>
                  <Input
                    size="small"
                    placeholder="自定义值"
                    onBlur={(e) => {
                      const val = (e.target as HTMLInputElement).value.trim();
                      if (val) {
                        handleChange(key, val);
                      }
                    }}
                  />
                </div>
              </>
            )}
          />
        </Space>
      ))}

      <div>
        <Paragraph copyable strong>
          当前表达式: {expression}
        </Paragraph>
        <Paragraph type="secondary">说明：{explainCron(expression)}</Paragraph>
        {isValid ? (
          <Alert type="success" message="表达式格式合法" />
        ) : (
          <Alert type="warning" message="表达式格式不合法，请检查每个字段" />
        )}
      </div>

      <div>
        <Text strong>快捷模板：</Text>
        <Space wrap>
          {quickTemplates.map((tpl) => (
            <Button key={tpl.label} onClick={() => handleQuickSet(tpl.value)}>
              {tpl.label}
            </Button>
          ))}
        </Space>
      </div>
    </Space>
  );
};

export default CronGenerator;
